package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.CourseDescMapper;
import com.jt.mapper.CourseMapper;
import com.jt.mapper.ItemDescMapper;
import com.jt.pojo.Course;
import com.jt.pojo.CourseDesc;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.CourseVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService{

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseDescMapper courseDescMapper;


    @Override
    public PageResult getCourseList(PageResult pageResult) {
        //1.构建分页对象  参数1: 第几页   参数2: 多少条
        Page<Course> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        //2.准备条件构造器 构建模糊查询
        QueryWrapper queryWrapper = new QueryWrapper();
        String query = pageResult.getQuery();
        boolean flag = StringUtils.hasLength(query);
        queryWrapper.like(flag,"course_name",query);
        //3.根据MP查询 实现分页数据的自动封装
        page = courseMapper.selectPage(page,queryWrapper);
        //4.获取数据,返回分页对象
        long total = page.getTotal();
        //获取分页结果
        List<Course> rows = page.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional //控制事务
    public void updateCourseStatus(Course course) {
        courseMapper.updateById(course);
    }

    @Override
    @Transactional //控制事务
    public void deleteCourseById(Course course) {
        courseMapper.deleteById(course.getCourseId());
        courseMapper.deleteById(course.getCourseId());
    }

    @Override
    @Transactional //控制事务
    public void updateCourseById(Course course) {
        courseMapper.updateById(course);
    }

    @Override
    public void saveCourse(CourseVO courseVO) {
        Course course = courseVO.getCourse();
        //设定状态
        course.setStatus(true);
        courseMapper.insert(course); //数据信息自动回显
        //获取商品详情
        CourseDesc courseDesc = courseVO.getCourseDesc();
//        courseDesc.setId(course.getCourseId());
        courseDesc.setCourseId(course.getCourseId());
        courseDescMapper.insert(courseDesc);
    }


}
